package logic

import (
	"context"
	"fmt"
	"net/http"
	"rpc/turn"
	"strconv"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AliPayLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAliPayLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AliPayLogic {
	return &AliPayLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AliPayLogic) AliPay(w http.ResponseWriter, r *http.Request) (resp *types.AliPayResponse, err error) {
	// todo: add your logic here and delete this line
	fmt.Println(r)

	orderSn := r.FormValue("out_trade_no")

	status := r.FormValue("trade_status")

	if status == "TRADE_SUCCESS" {
		status = "1" //支付成功
	}
	if status == "WAIT_BUYER_PAY" {
		status = "2" // 未支付，等待支付
	}
	if status == "TRADE_CLOSED" {
		status = "3" //已退款
	}
	if status == "TRADE_FINISHED" {
		status = "4" //交易结束
	}
	Status, _ := strconv.Atoi(status)

	_, err = l.svcCtx.Turn.UpdateOrderStatus(l.ctx, &turn.UpdateOrderStatusRequest{
		OrderSn: orderSn,
		Status:  int64(Status),
	})
	if err != nil {
		return nil, err
	}

	return
}
